package com.czy;

import gui.ava.html.image.generator.HtmlImageGenerator;
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;

import javax.imageio.ImageIO;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.net.URL;
import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

public class List和Excel数据转图片 {

    public static void main(String[] args) throws IOException {
        List<LinkedHashMap<String, String>> list = new ArrayList<>();
        LinkedHashMap<String, String> map = new LinkedHashMap<>();
        map.put("姓名","张三");
        map.put("性别","男");
        map.put("年龄","18");
        list.add(map);

        LinkedHashMap<String, String> map1 = new LinkedHashMap<>();
        map1.put("姓名","李四");
        map1.put("性别","男");
        map1.put("年龄","19");
        list.add(map1);

        File file = convertToImage(list, "D:\\listToImg.png");
        System.out.println(file);

        List<LinkedHashMap<String, String>> list1 = readExcelFile("C:\\Users\\Administrator\\Desktop\\test.xlsx");
        File file1 = convertToImage(list1, "D:\\excelToImg.png");
        System.out.println(file1);
    }

    /**
     * 将List转换为图片
     * @param list 数据
     * @param filePath 图片保存路径
     */
    public static File convertToImage(List<LinkedHashMap<String, String>> list, String filePath) throws IOException {
        String s = generateHtml(list);
        File file = new File(filePath);
        generateImage(s,filePath);
        return file;
    }

    /**
     * 读取Excel文件（保持列顺序）
     */
    public static List<LinkedHashMap<String, String>> readExcelFile(String filePath) throws IOException {
        List<LinkedHashMap<String, String>> dataList = new ArrayList<>();

        try (FileInputStream fileInputStream = new FileInputStream(filePath);
             Workbook workbook = new XSSFWorkbook(fileInputStream)) {

            Sheet sheet = workbook.getSheetAt(0); // 读取第一个sheet

            // 读取表头（第一行）
            Row headerRow = sheet.getRow(0);
            List<String> headers = new ArrayList<>();
            if (headerRow != null) {
                for (Cell cell : headerRow) {
                    headers.add(getCellValue(cell));
                }
            }

            System.out.println("检测到表头: " + headers);

            // 读取数据行（从第二行开始）
            for (int i = 1; i <= sheet.getLastRowNum(); i++) {
                Row row = sheet.getRow(i);
                if (row != null) {
                    LinkedHashMap<String, String> rowData = new LinkedHashMap<>();
                    for (int j = 0; j < headers.size(); j++) {
                        Cell cell = row.getCell(j, Row.MissingCellPolicy.CREATE_NULL_AS_BLANK);
                        rowData.put(headers.get(j), getCellValue(cell));
                    }
                    dataList.add(rowData);
                }
            }
        }

        return dataList;
    }

    /**
     * 获取单元格值
     */
    private static String getCellValue(Cell cell) {
        if (cell == null) return "";

        switch (cell.getCellType()) {
            case STRING:
                return cell.getStringCellValue().trim();
            case NUMERIC:
                if (DateUtil.isCellDateFormatted(cell)) {
                    return cell.getDateCellValue().toString();
                } else {
                    // 判断是否为整数
                    double num = cell.getNumericCellValue();
                    if (num == Math.floor(num)) {
                        return String.valueOf((int) num);
                    } else {
                        return String.valueOf(num);
                    }
                }
            case BOOLEAN:
                return String.valueOf(cell.getBooleanCellValue());
            case FORMULA:
                return cell.getCellFormula();
            default:
                return "";
        }
    }

    /**
     * 生成HTML内容 - 简化样式版本
     */
    private static String generateHtml(List<LinkedHashMap<String, String>> dataList) {
        if (dataList.isEmpty()) {
            return "<html><body><h2>没有数据</h2></body></html>";
        }

        // 获取表头（使用第一行数据的key）
        List<String> headers = new ArrayList<>(dataList.get(0).keySet());

        StringBuilder html = new StringBuilder();
        html.append("<!DOCTYPE html>\n")
                .append("<html>\n")
                .append("<head>\n")
                .append("    <meta charset=\"UTF-8\">\n")
                .append("    <style>\n")
                .append("        body { font-family: Arial, sans-serif; padding: 10px;}\n")
                .append("        table { border-collapse: collapse; width: 100%; }\n")
                .append("        th, td { border: 1px solid #000; padding: 8px; text-align: center; }\n")
                .append("        th { background-color: #f2f2f2; font-weight: bold; }\n")
                .append("    </style>\n")
                .append("</head>\n")
                .append("<body>\n")
                .append("    <table>\n")
                .append("        <thead>\n")
                .append("            <tr>\n");

        // 添加表头
        for (String header : headers) {
            html.append("                <th>").append(header).append("</th>\n");
        }

        html.append("            </tr>\n")
                .append("        </thead>\n")
                .append("        <tbody>\n");

        // 添加数据行
        for (Map<String, String> rowData : dataList) {
            html.append("            <tr>\n");
            for (String header : headers) {
                String value = rowData.getOrDefault(header, "");
                html.append("                <td>").append(value).append("</td>\n");
            }
            html.append("            </tr>\n");
        }

        html.append("        </tbody>\n")
                .append("    </table>\n")
                .append("</body>\n")
                .append("</html>");

        return html.toString();
    }

    /**
     * 生成图片
     */
    private static void generateImage(String htmlContent, String outputPath) throws IOException {
        HtmlImageGenerator generator = new HtmlImageGenerator();

        generator.loadHtml(htmlContent);
        BufferedImage bufferedImage = generator.getBufferedImage();

        // 保存图片
        File outputFile = new File(outputPath);
        ImageIO.write(bufferedImage, "png", outputFile);
    }
}
